<?php

namespace App\Http\Controllers\Manage;

use App\Http\Controllers\ApiController;
use App\Http\Requests\MarriageHistoryStoreRequest;
use App\Http\Requests\MarriageHistoryUpdateRequest;
use App\Models\MarriageHistory;
use App\Models\MedicalRecord;
use App\Models\Patient;
use App\Project\Filters\MarriageHistoryFilter;
use App\Project\Transform;
use App\Transformers\MarriageHistoryTransformer;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

class MarriageHistoryController extends ApiController
{
    /**
     * @param \App\Http\Requests\MarriageHistoryStoreRequest $request
     * @param \App\Models\MarriageHistory                    $history
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(MarriageHistoryStoreRequest $request, MarriageHistory $history)
    {
        $this->extendValidation($request, $record_id = $request->input('record_id'));

        $patient = (new MedicalRecord())->getWithCache($record_id)->patient;

        if (!$patient->female()) {
            $history->fillable(['marriage', 'remark', 'record_id']);
        }

        $input = (new MarriageHistoryFilter($request))->input();

        $history->fill($input)->save();

        return $this->response(['id' => $history->id]);
    }

    /**
     * 拓展验证
     * @param \Illuminate\Http\Request $request
     * @param                          $record_id
     */
    protected function extendValidation(Request $request, $record_id)
    {
        $record = (new MedicalRecord())->getWithCache($record_id);

        $patient =  Patient::findOrFail($record->patient_id);

        $this->validate($request, [
            'marriage.time' => 'after:' . $patient->birthday
        ], [
            'marriage.time.after' => '结婚日期需要大于出生日期'
        ]);
    }


    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        $data = null;
        $id   = $request->get('id');

        if ($id > 0) {

            $data = MarriageHistory::findOrFail($id);
        } elseif ($record_id = $request->get('record_id')) {

            $data = MarriageHistory::where(['record_id' => $record_id])->first();
        } else {
            abort(400, '缺失月经婚育史ID，或者病历ID');
        }

        if (empty($data)) {
            throw (new ModelNotFoundException())->setModel(MarriageHistory::class);
        }

        return $this->item($data, new MarriageHistoryTransformer());
    }

    /**
     * @param \App\Http\Requests\MarriageHistoryUpdateRequest $request
     * @param \App\Models\MarriageHistory                     $history
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(MarriageHistoryUpdateRequest $request, MarriageHistory $history)
    {
        $this->extendValidation($request, $record_id = $request->input('record_id'));

        $where = [];

        if ($id = $request->input('id')) {
            $where['id'] = $id;
        } else {
            $where['record_id'] = $record_id;
        }

        $input = (new MarriageHistoryFilter($request))->except(['id', 'record_id']);

        $input = (new Transform())->setArray($input)->convertArrayToJson(
            ['marriage', 'menstruation', 'menopause']
        )->get();

        if (!is_null($input['macrosomia']))
            $input['macrosomia'] = $input['macrosomia'] ? 1 : 0;

        $patient = (new MedicalRecord())->getWithCache($record_id)->patient;

        if (!$patient->female()) {
            $input = array_intersect_key($input, array_flip(['marriage', 'remark']));
        }

        $result = $history->where($where)->update($input);

        return $this->responseForUpdate($result);
    }
}
